package com.eims.sls_app.fragment;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.text.Spanned;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestParams;
import bls.juejin.cn.R;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.ui.AccountInformationActivity;
import com.eims.sls_app.ui.CustomerActivity;
import com.eims.sls_app.ui.FundsInfoActivity;
import com.eims.sls_app.ui.GamecenterActivity;
import com.eims.sls_app.ui.IntegralCenterAcitvity;
import com.eims.sls_app.ui.Luck_drawActivity;
import com.eims.sls_app.ui.MainActivity;
import com.eims.sls_app.ui.MoneyZcActivity;
import com.eims.sls_app.ui.MyAllAccountLotteryActivity;
import com.eims.sls_app.ui.MyAllLotteryActivity;
import com.eims.sls_app.ui.PayWebActivity;
import com.eims.sls_app.ui.PerfectdataActivity;
import com.eims.sls_app.ui.SelectRechargeTypeActivity;
import com.eims.sls_app.ui.SettingActivity;
import com.eims.sls_app.ui.SpreadActivity;
import com.eims.sls_app.ui.TransferActivity;
import com.eims.sls_app.ui.WithdrawalActivity;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.AppTools;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.ImageManager;
import com.eims.sls_app.utils.LotteryUtils;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyToast;
import com.eims.sls_app.view.XCRoundImageView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.wx.roundimageview.RoundDrawable;
import com.wx.roundimageview.RoundImageView;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * 个人中心
 */
@SuppressLint("NewApi")
public class MyCenterFragment extends Fragment implements OnClickListener {

	private static final String TAG = "MyCenterFragment";
	private PullToRefreshScrollView my_center_scrollView;
	private LinearLayout btn_all, btn_lottery, btn_in_lottery, btn_follow, btn_chipped, btn_user, btn_detail,
			btn_integral_detail, btn_integral_detail_copy, lr_hongbao, lr_hongbao_info,lr_spread,lr_zz;
	private XCRoundImageView iv_icon;
	private ImageButton btn_back, btn_setting;
	private TextView tv_name, tv_balance, tv_freeze;
	private String opt, auth, info, time, imei, crc; // 格式化后的参数
	private Context context;
	private MyHandler mHandler;
	private ProgressDialog proDialog;
	// 新增控件
	private LinearLayout linearPay; // 充值
	private LinearLayout linearName;
	private LinearLayout linearDrawMoney;// 提现
	private static final int PIC1 = 1;
	private static final int PIC2 = 2;

	private TextView tvCaiJin;

	private View view_shape;
	private LinearLayout mIvIconService;
	
	private String isBinded;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		context = getActivity();
		View v = inflater.inflate(R.layout.activity_my_center, container, false);
		mHandler = new MyHandler();
		findView(v);
		setListener();


		return v;
	}

	/** 初始化UI */
	private void findView(View v) {
		// 退出按钮

		mIvIconService = (LinearLayout) v.findViewById(R.id.iv_icon_service);
		my_center_scrollView = (PullToRefreshScrollView) v.findViewById(R.id.my_center_scrollView);
		btn_back = (ImageButton) v.findViewById(R.id.btn_back);
		btn_all = (LinearLayout) v.findViewById(R.id.btn_all);
		btn_lottery = (LinearLayout) v.findViewById(R.id.btn_lottery);
		btn_in_lottery = (LinearLayout) v.findViewById(R.id.btn_in_lottery);
		btn_follow = (LinearLayout) v.findViewById(R.id.btn_follow);
		btn_chipped = (LinearLayout) v.findViewById(R.id.btn_chipped);
		btn_user = (LinearLayout) v.findViewById(R.id.btn_userInfo);
		btn_detail = (LinearLayout) v.findViewById(R.id.btn_detail);
		btn_integral_detail = (LinearLayout) v.findViewById(R.id.btn_integral_detail);
		btn_setting = (ImageButton) v.findViewById(R.id.btn_setting);
		tv_name = (TextView) v.findViewById(R.id.center_tv_name);
		tv_balance = (TextView) v.findViewById(R.id.tv_freeze);
		tv_freeze = (TextView) v.findViewById(R.id.tv_freeze2);
		iv_icon = (XCRoundImageView) v.findViewById(R.id.iv_icon);
		// 初始化新增控件
		linearPay = (LinearLayout) v.findViewById(R.id.Linear_pay);
		linearDrawMoney = (LinearLayout) v.findViewById(R.id.Linear_draw_money);
		linearName = (LinearLayout) v.findViewById(R.id.ll_name);
		tvCaiJin = (TextView) v.findViewById(R.id.tv_caijin);

		lr_hongbao = (LinearLayout) v.findViewById(R.id.Linear_draw_hongbao_info);
		lr_hongbao_info = (LinearLayout) v.findViewById(R.id.Linear_draw_hongbao);
		btn_integral_detail_copy = (LinearLayout) v.findViewById(R.id.btn_integral_detail_copy);
		view_shape = v.findViewById(R.id.view_shape);
		lr_spread= (LinearLayout) v.findViewById(R.id.iv_icon_spread);
		lr_zz= (LinearLayout) v.findViewById(R.id.iv_icon_zz);

		// 从view层级，关闭硬件加速，否则在Android 4.0之后设置虚线属性，依然显示为实线
		view_shape.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
	}

	/** 绑定监听 */
	private void setListener() {
		mIvIconService.setOnClickListener(this);
		btn_back.setOnClickListener(this);
		btn_all.setOnClickListener(this);
		btn_lottery.setOnClickListener(this);
		btn_in_lottery.setOnClickListener(this);
		btn_follow.setOnClickListener(this);
		btn_chipped.setOnClickListener(this);
		btn_user.setOnClickListener(this);
		linearName.setOnClickListener(this);
		lr_hongbao.setOnClickListener(this);
		lr_hongbao_info.setOnClickListener(this);

		btn_integral_detail_copy.setOnClickListener(this);
		lr_spread.setOnClickListener(this);
		// 替换充值
		linearPay.setOnClickListener(this);
		// btn_draw_money.setOnClickListener(this);
		// 替换提现
		linearDrawMoney.setOnClickListener(this);
		btn_detail.setOnClickListener(this);
		btn_integral_detail.setOnClickListener(this);
		btn_setting.setOnClickListener(this);

		lr_zz.setOnClickListener(this);
		my_center_scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				my_center_scrollView.getLoadingLayoutProxy(true, false)
						.setLastUpdatedLabel("最近更新: " + LotteryUtils.Long2DateStr_detail(System.currentTimeMillis()));
				doAutoLogin();
			}
		});
	}

	/** 公用点击监听 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.iv_icon_spread:
				Intent Spreadintent = new Intent(context, SpreadActivity.class);
				Bundle bundle=new Bundle();
				bundle.putString("url",App.user.getCode());
				Spreadintent.putExtras(bundle);
				context.startActivity(Spreadintent);

				break;
			case R.id.iv_icon_zz:
				if (0> Double.parseDouble(App.user.getBalance())) {
					MyToast.getToast(getActivity(), "可用余额为0，不能转存！").show();
				} else {
					Intent Moneyintent = new Intent(context, MoneyZcActivity.class);
					Bundle Moneybundle=new Bundle();
					Moneybundle.putString("balance",App.user.getBalance());
					Moneyintent.putExtras(Moneybundle);
					context.startActivity(Moneyintent);
				}

				break;
		case R.id.Linear_draw_hongbao_info:
			// Toast.makeText(context, "功能开发中，敬请期待！", Toast.LENGTH_SHORT).show();
			Intent Hongbaointent = new Intent(context, MyAllAccountLotteryActivity.class);
			context.startActivity(Hongbaointent);

			break;
		case R.id.Linear_draw_hongbao:
//			Toast.makeText(context, "功能开发中，敬请期待！", Toast.LENGTH_SHORT).show();
			Intent Transferintent = new Intent(context, TransferActivity.class);
			startActivityForResult(Transferintent, 101);
			break;
		case R.id.iv_icon_service:
			Intent intent1 = new Intent(getActivity(), CustomerActivity.class);
			startActivity(intent1);
			break;

		case R.id.btn_integral_detail_copy:
			ToOtherActivity(3);
			break;
		case R.id.btn_back:
			break;
		case R.id.btn_all:
			ToOtherActivity(0);
			break;
		case R.id.btn_lottery:
			ToOtherActivity(1);
			break;
		case R.id.btn_in_lottery:
			ToOtherActivity(2);
			break;
		case R.id.btn_follow:
			ToOtherActivity(5);
			break;
		case R.id.btn_chipped:
			ToOtherActivity(4);
			break;
		case R.id.btn_setting:
			Intent intent = new Intent(context, SettingActivity.class);
			context.startActivity(intent);
			break;

		case R.id.btn_userInfo:
			intent = new Intent(context, AccountInformationActivity.class);
			context.startActivity(intent);
			break;

		case R.id.Linear_pay:
			// 跳到充值页面
			intent = new Intent(context, SelectRechargeTypeActivity.class);
			startActivityForResult(intent, PIC2);
			// intentPayWebActivity();
			break;
		case R.id.Linear_draw_money:
			if (10 > Double.parseDouble(App.user.getBalance())) {
				MyToast.getToast(getActivity(), "可用余额不足，不能提款！").show();
			} else {
				MyAsynTask mMyAsynTask = new MyAsynTask();
				mMyAsynTask.execute();
			}
			break;
		case R.id.btn_detail:
			// intent = new Intent(context, FundsInfoActivity.class);
			Intent Myintent = new Intent(context, MyAllAccountLotteryActivity.class);
			context.startActivity(Myintent);
			break;
		case R.id.btn_integral_detail:// 积分中心
			intent = new Intent(context, IntegralCenterAcitvity.class);
			context.startActivity(intent);
			break;

		case R.id.ll_name:
			intent = new Intent(context, PerfectdataActivity.class);
			startActivityForResult(intent, PIC1);

			break;

		}
	}

	private void intentPayWebActivity() {
		Intent intent = new Intent();
		intent.setClass(context, PayWebActivity.class);
		startActivityForResult(intent, 200);
	}

	// @Override
	// public void onActivityResult(int requestCode, int resultCode, Intent
	// data) {
	// switch (resultCode)
	// {
	// case 200:
	// my_center_scrollView.smoothScrollTo0();
	// break;
	//
	// }
	// }

	/** 初始化参数 */
	private void init() {
		opt = "41";
		time = RspBodyBaseBean.getTime();
		imei = RspBodyBaseBean.getIMEI(context);
		info = "{}";
		// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
		String key = App.key;
		crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
		auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
	}

	/** 公用跳转方法 */
	private void ToOtherActivity(int lotteryType) {
		Intent intent = new Intent(context, MyAllLotteryActivity.class);
		intent.putExtra("index", lotteryType);
		context.startActivity(intent);
	}

	@Override
	public void onResume() {
		if (null == App.user) {
			Log.i("x", "调用了。。。。。。。");
			Intent intent = new Intent(context, MainActivity.class);
			context.startActivity(intent);

		} else {
			if (App.user.getBalance().equals("NaN")) {
				doAutoLogin();
			}
			tv_balance.setText(App.user.getBalance() + "");
			tv_freeze.setText(App.user.getScoring() + "");
			tvCaiJin.setText(App.user.getHandselAmount() + "");
			tv_name.setText(App.user.getName());

			ImageManager.getInstance().displayImage(App.user.getHeadUrl(), iv_icon, ImageManager.getViewsHeadOptions());
			Log.e("5", "oncreateView()");
			String code= App.user.getCode();

//			Log.e("----",code);
			if (code==null||code.equals("")){

				lr_spread.setVisibility(View.INVISIBLE);

			}else {

				lr_spread.setVisibility(View.VISIBLE);

			}
		}
		super.onResume();
	}

	/**
	 * 异步任务
	 */
	class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {

			// if (null == App.user.getRealityName() || App.user.getRealityName().length()
			// == 0) {
			// return error;
			// } else if (null == App.user.getBangNum()) {
			// init();
			opt = "41";

			Log.e(TAG, "doInBackground: "+opt);
			time = RspBodyBaseBean.getTime();
			imei = RspBodyBaseBean.getIMEI(context);
			info = "{}";
			// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
			String key = App.key;
			crc = RspBodyBaseBean.getCrc(time, imei, key, info, App.user.getUid());
			auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
			String[] values = { opt, auth, info };
			String result = HttpUtils.doPost(App.names, values, App.path);

			Log.e("---", result);

			JSONObject object = null;
			try {
				object = new JSONObject(result);
				isBinded = object.optString("isBinded");
				// if ("Yes".equals(isBinded)) {

				App.user.setBangNum(object.optString("bankCardNumber"));
				App.user.setProvinceName(object.optString("provinceName"));
				App.user.setCityName(object.optString("cityName"));
				App.user.setBankName(object.optString("bankTypeName"));
				App.user.setFullName(object.optString("branchBankName"));
				App.user.setSecurityQuestionId(object.optString("securityquestion"));
                App.user.setSecurityQuestionIndex(object.optString("securityQuestionId"));
				App.user.setRealityName(object.optString("realityName"));
				App.user.setQqNumber(object.optString("qqnumber"));
				App.user.setIdcardnumber(object.optString("idCardnumber"));
				App.user.setMobile(object.optString("mobile"));

				error = "0";

			} catch (Exception e) {
				e.printStackTrace();
				error = "1";

			}

			// } else {
			// error = "-2";
			// Log.e("x", "银行卡没绑定");
			// }

			// } else {
			// error = "0";
			// }
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			Log.e("---", App.user.toString());
			Log.e("---", result);

			mHandler.sendEmptyMessage(Integer.parseInt(result));
			super.onPostExecute(result);
		}
	}

	@SuppressLint("HandlerLeak")
	class MyHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			if (proDialog != null) {
				proDialog.dismiss();
			}
			Intent mIntent;
			switch (msg.what) {
			case 0:

				String str2 = App.user.getBangNum();
				if (str2.length() > 6) {
					App.user.setBangNum(str2.substring(0, 3) + "***" + str2.substring(str2.length() - 3));
				}

				if (null == App.user.getRealityName() || App.user.getRealityName().length() == 0) {
					mHandler.sendEmptyMessage(-1);

				} else if (null == App.user.getBangNum()) {
					if ("Yes".equals(isBinded)) {
						mHandler.sendEmptyMessage(3);
					} else {
						mHandler.sendEmptyMessage(-2);
					}

				} else {
					mHandler.sendEmptyMessage(3);
				}
				break;
			case -1:
				MyToast.getToast(context, "请先绑定身份证信息").show();
				mIntent = new Intent(context, AccountInformationActivity.class);
				context.startActivity(mIntent);
				break;
			case -2:
				MyToast.getToast(context, "请先绑定银行信息").show();
				mIntent = new Intent(context, AccountInformationActivity.class);
				context.startActivity(mIntent);
				break;

			case 3:
				mIntent = new Intent(context, WithdrawalActivity.class);
				context.startActivity(mIntent);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	}

	/**
	 * 重新登录，刷新数据。
	 */
	public void doAutoLogin() {
		RequestUtil requestUtil = new RequestUtil(context, false, 0) {
			@Override
			public void responseCallback(JSONObject reponseJson) {
				String retult = AppTools.doLogin(reponseJson);
				if ("0".equals(retult)) {
					my_center_scrollView.onRefreshComplete();
					onResume();
					SharedPreferences settings = context.getSharedPreferences("app_user", 0);
					boolean isLogin = false;
					String pass = "";
					if (settings.contains("isLogin")) {
						isLogin = settings.getBoolean("isLogin", false);
					}
					if (isLogin) {
						// 判断是否有存 密码
						if (settings.contains("pass")) {
							pass = settings.getString("pass", null);
						}
					}
					if (null != App.user)
						App.user.setUserPass(pass);
				}
			}

			@Override
			public void responseError(VolleyError error) {
				RequestParams.convertError(context, error, true);
			}
		};
		requestUtil.doAutoLogin();
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		doAutoLogin();
		switch (resultCode) {
		case PIC1:
			String urlString = data.getStringExtra("url");
			ImageManager.getInstance().displayImage(urlString, iv_icon, ImageManager.getViewsHeadOptions());
			break;
		}
	}
}
